package queue;

/**
 * Created by byakuya on 2020/7/20
 * 循环队列
 */
public class MyCircularQueue {

    private int front = -1;
    private int rear = -1;
    private int[] q;
    private int size;
    /* 队列长度为 k */
    public MyCircularQueue(int k) {
        q = new int[k];
        size = k;
    }

    /* 插入元素，成功为真 */
    public boolean enQueue(int value) {
        if(!isFull()){
            if (rear == -1)
                front = 0;
            rear = (rear + 1) % size;
            q[rear] = value;
            return true;
        }else{
            return false;
        }
    }

    /* 删除元素，成功返回真 */
    public boolean deQueue() {
        if (!isEmpty()){
            if (front == rear){
                rear = front = -1;
            }
            else
                front = (front + 1) % size;
            return true;
        }else {
            return false;
        }
    }

    /* 获取队首元素 */
    public int Front() {
        if (isEmpty())
            return -1;
        return q[front];
    }

    /* 获取队尾元素 */
    public int Rear() {
        if (isEmpty())
            return -1;
        return q[rear];
    }

    /* 队列是否为空 */
    public boolean isEmpty() {
        return front == -1;
    }

    /* 队列是否已满 */
    public boolean isFull() {
        return (rear +  1) % size == front;
    }

    public void print(){
        for(int x : q){
            System.out.print(" " + x);
        }
        System.out.println();
    }
}
